var explorer = {};

explorer.Explorer = function(){};
core.extendClass('explorer.Explorer', 'core.JSApplication');

explorer.TreePanel = function(){};
core.extendClass('explorer.TreePanel', 'core.JSFrame');

explorer.TreePanel.prototype.reloadTree = function(){
    var instance = this;
    this.sendMessage('getTree', {}, function(data){
        instance.tree.loadTree(data);
    }, null, this.tree);
};

explorer.TreePanel.prototype.treeItemModified = function(aData){
    this.tree.treeItemModified(aData);
}

explorer.TreePanel.prototype.treeItemRemoved = function(aData){
    this.tree.treeItemRemoved(aData);
}

explorer.TreePanel.prototype.treeItemInserted = function(aData){
    this.tree.treeItemInserted(aData);
}

explorer.TreePanel.prototype.changeTreeItemState = function(aData){
    this.tree.changeTreeItemState(aData);
}

explorer.TreePanel.prototype.setShowHiddenTitle = function(aHidden){
    this.showHidden.text = aHidden? 'Hide hidden files':'Show hidden files';
};

explorer.TreePanel.prototype.loadContents = function(aData){
    var instance = this;
    this.newElementBtn = new core.form.Button({
        text: 'New file...',
        menu: []
    });
    this.newElementBtn.setDisabled(true);
    this.newWindowBtn = new core.form.Button({
        text: 'New window',
        handler: function(){
            instance.application.sendMessage('newWindow');
        }
    });
    this.hiddenFiles = aData.showHidden || false;
    this.showHidden = {
        handler: function(){
            instance.hiddenFiles = !instance.hiddenFiles;
            instance.setShowHiddenTitle(instance.hiddenFiles);
            instance.send({
                method: 'changeShowHidden',
                disable: instance.tree
            });
            return true;
        }
    };
    this.setShowHiddenTitle(this.hiddenFiles);
    this.viewBtn = new core.form.Button({
        text: 'View',
        menu: [
            this.showHidden
        ]
    });
    var toolbar = new core.Tabs({
        cls: 'toolbar',
        toolbar: true
    });
    toolbar.addTab(this.newWindowBtn, this.newElementBtn, this.viewBtn);
    this.frame.addToolbar(toolbar);
    this.tree = new core.tree.TreePanel({

    });
    this.setContent([this.tree], '1', '1');

    this.tree.on('item_click', function(tree, e, item){
        if(e && e.shiftKey){
//            core.log('Open viewer in new win', item.id);
            instance.sendMessage('openNewViewer', {
                id: item.id
            }, null, function(code, text){
                instance.application.showError(text);
            }, null);
        }
    });

    this.tree.on('item_dbl_click', function(tree, e, item){
//            core.log('Open viewer in new win', item.id);
        instance.sendMessage('elementDblClick', {
            id: item.id
        });
    });

    this.tree.on('state_change', function(tree, event, item){
//        core.log('Sending state of item of '+item.id, 'to', item.collapsed);
        instance.sendMessage('setState', {
            id: item.id,
            collapsed: item.collapsed
        });
    });

    this.tree.on('load', function(tree, event, item){
//        core.log('need to load element: '+item.id);
        instance.sendMessage('loadItems', {
            id: item.id
        }, function(aData){
            instance.tree.loadItems(item, aData);
//            item.clear();
//            var arr = $.makeArray(aData.children);
//            if(!aData.collapsed && arr.length>0){
//                for (var i = 0; i < arr.length; i++) {
//                    instance.loadTreeItem(arr[i], item);
//                }
////                item.loadComplete(false);
////            }else
//            }
//            item.loadComplete(false);
        }, function(code, text){
            instance.application.showError(text);
        });
    });

    this.tree.on('select', function(tree, event, item){
        var id = '';
        if(item)
            id = item.id;
//        core.log('selected element: ', id);
//        instance.newElementBtn.markLoading();
        instance.send({
            method: 'selectionChanged',
            message: {
                id: id
            },
            ok: function(data){
            var menu = [];
            var arr = $.makeArray(data.file_types);
                for (var i = 0; i < arr.length; i++) {
                    menu.push({
                        id: arr[i].code,
                        text: arr[i].name,
                        cls: arr[i].icon
                    });
                }
                instance.newElementBtn.menu = menu;
                instance.newElementBtn.setDisabled(menu.length==0);
            },
            disable: instance.application.getFrameElement('file-viewer') || instance.frame
        });
    });
    this.newElementBtn.on('menu_select', function(i, e, item){
        instance.send({
            method: 'newFile',
            message: {
                type: item.id
            },
            disable: instance.tree
        });
    })
    this.reloadTree();
};

explorer.ViewPanel = function(){};
core.extendClass('explorer.ViewPanel', 'core.JSFrame');

explorer.ViewPanel.prototype.sendMessageToViewer = function(aData, aOkHandler, aErrorHandler){
    var instance = this;
    this.sendMessage('messageToViewer', aData, aOkHandler, aErrorHandler?aErrorHandler:function(code, text){
        instance.application.showError(text);
    }, this.currentViewer);
};

explorer.ViewPanel.prototype.displayFile = function(aData){
    this.editBtn.setDisabled(!aData.editable);
    this.reloadBtn.setDisabled(!aData.reloadable);
    this.removeBtn.setDisabled(!aData.removable);
    var arr = $.makeArray(aData.open_as);
    var menu = [];
    for (var i = 0; i < arr.length; i++) {
        menu.push({
            id: arr[i].id,
            text: arr[i].name,
            cls: arr[i].icon
        });
    }
    this.openAsBtn.menu = menu;
    this.openAsBtn.setDisabled(menu.length==0);
    this.fileID = aData.id;
    var replaceWith = this.emptyFile;
    var instance = this;
//    core.log('Creating viewer...');
    if(aData.viewer_class){
        var constructor = core.findElementByItsName(aData.viewer_class);
        if(constructor){
            replaceWith = new constructor();
            replaceWith.init({
                data: aData.viewer_object || {},
                frame: instance
            });
        }else{
//            core.log('Cant find constructor');
        }
    }else{
//        core.log('cant find class');
    }
    var hideType = core.REPLACE_CHILD_DESTROY;
    if(this.currentViewer == this.emptyFile)
        hideType = core.REPLACE_CHILD_HIDE;
    this.frame.body.replaceChild(this.currentViewer, replaceWith, hideType);
    this.frame.updateLayout();
    this.refresh(replaceWith, true);
    this.currentViewer = replaceWith;
//    core.log('Display file complete');
};

explorer.ViewPanel.prototype.loadContents = function(){
    var instance = this;
    this.mainToolbar = new core.Tabs({
        toolbar: true,
        cls: 'toolbar'
    });
    this.frame.addToolbar(this.mainToolbar);
    this.editBtn = new core.form.Button({
        text: 'Edit',
        handler: function(){
            instance.sendMessage("editFile", {
                id: instance.fileID
            }, null, function(code, text){
                instance.application.showError(text);
            }, instance.editBtn);
        }
    });
    this.removeBtn = new core.form.Button({
        text: 'Remove',
        handler: function(){
            instance.sendMessage("removeFile", {
                id: instance.fileID
            }, function(){
                if(instance.dynamic)
                    instance.requestClose();
            }, function(code, text){
                instance.application.showError(text);
            }, instance.editBtn);
        }
    });
    this.reloadBtn = new core.form.Button({
        text: 'Reload',
        handler: function(){
            instance.sendMessage("refreshPanel", null, null, null,
            instance.reloadBtn);
        }
    });
    this.openAsBtn = new core.form.Button({
        text: 'Open as...',
        menu: []
    });
    this.openAsBtn.on('menu_select', function(i, e, item){
        instance.send({
            method: 'openAs',
            message: {
                type: item.id
            },
            disable: instance.frame
        });
    });
    this.mainToolbar.addTab(this.editBtn, this.removeBtn, this.reloadBtn, this.openAsBtn);
    this.editBtn.setDisabled(true);
    this.removeBtn.setDisabled(true);
    this.reloadBtn.setDisabled(true);
    this.openAsBtn.setDisabled(true);
    this.emptyFile = new core.Label({
        text: '',
        align: 'left'
    });
    this.currentViewer = this.emptyFile;
    this.setContent([this.emptyFile], '1', '1');
    if(this.dynamic){
        this.sendMessage('refreshPanel', {});
    }
};
